/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities.dao;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Contentpage;
import entities.Contentindex;
import entities.Post;
import entities.PostPK;
import entities.dao.exceptions.NonexistentEntityException;
import entities.dao.exceptions.PreexistingEntityException;
import entities.dao.exceptions.RollbackFailureException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Emmanuel
 */
public class DAOPost implements Serializable {

    public DAOPost(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Post post) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (post.getPostPK() == null) {
            post.setPostPK(new PostPK());
        }
        post.getPostPK().setIdContentIndex(post.getContentindex().getId());
        post.getPostPK().setIdContentPage(post.getContentpage().getId());
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Contentpage contentpage = post.getContentpage();
            if (contentpage != null) {
                contentpage = em.getReference(contentpage.getClass(), contentpage.getId());
                post.setContentpage(contentpage);
            }
            Contentindex contentindex = post.getContentindex();
            if (contentindex != null) {
                contentindex = em.getReference(contentindex.getClass(), contentindex.getId());
                post.setContentindex(contentindex);
            }
            em.persist(post);
            if (contentpage != null) {
                contentpage.getPostList().add(post);
                contentpage = em.merge(contentpage);
            }
            if (contentindex != null) {
                contentindex.getPostList().add(post);
                contentindex = em.merge(contentindex);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findPost(post.getPostPK()) != null) {
                throw new PreexistingEntityException("Post " + post + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Post post) throws NonexistentEntityException, RollbackFailureException, Exception {
        post.getPostPK().setIdContentIndex(post.getContentindex().getId());
        post.getPostPK().setIdContentPage(post.getContentpage().getId());
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Post persistentPost = em.find(Post.class, post.getPostPK());
            Contentpage contentpageOld = persistentPost.getContentpage();
            Contentpage contentpageNew = post.getContentpage();
            Contentindex contentindexOld = persistentPost.getContentindex();
            Contentindex contentindexNew = post.getContentindex();
            if (contentpageNew != null) {
                contentpageNew = em.getReference(contentpageNew.getClass(), contentpageNew.getId());
                post.setContentpage(contentpageNew);
            }
            if (contentindexNew != null) {
                contentindexNew = em.getReference(contentindexNew.getClass(), contentindexNew.getId());
                post.setContentindex(contentindexNew);
            }
            post = em.merge(post);
            if (contentpageOld != null && !contentpageOld.equals(contentpageNew)) {
                contentpageOld.getPostList().remove(post);
                contentpageOld = em.merge(contentpageOld);
            }
            if (contentpageNew != null && !contentpageNew.equals(contentpageOld)) {
                contentpageNew.getPostList().add(post);
                contentpageNew = em.merge(contentpageNew);
            }
            if (contentindexOld != null && !contentindexOld.equals(contentindexNew)) {
                contentindexOld.getPostList().remove(post);
                contentindexOld = em.merge(contentindexOld);
            }
            if (contentindexNew != null && !contentindexNew.equals(contentindexOld)) {
                contentindexNew.getPostList().add(post);
                contentindexNew = em.merge(contentindexNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                PostPK id = post.getPostPK();
                if (findPost(id) == null) {
                    throw new NonexistentEntityException("The post with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(PostPK id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Post post;
            try {
                post = em.getReference(Post.class, id);
                post.getPostPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The post with id " + id + " no longer exists.", enfe);
            }
            Contentpage contentpage = post.getContentpage();
            if (contentpage != null) {
                contentpage.getPostList().remove(post);
                contentpage = em.merge(contentpage);
            }
            Contentindex contentindex = post.getContentindex();
            if (contentindex != null) {
                contentindex.getPostList().remove(post);
                contentindex = em.merge(contentindex);
            }
            em.remove(post);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Post> findPostEntities() {
        return findPostEntities(true, -1, -1);
    }

    public List<Post> findPostEntities(int maxResults, int firstResult) {
        return findPostEntities(false, maxResults, firstResult);
    }

    private List<Post> findPostEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Post.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Post findPost(PostPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Post.class, id);
        } finally {
            em.close();
        }
    }

    public int getPostCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Post> rt = cq.from(Post.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
